﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SharpDiary.Core.Common;
using SharpDiary.Core.Attributes;
using SharpDiary.Core.Utility;
using SharpDiary.Core.ORMapping;
using SharpDiary.Core.Data;

namespace SharpDiary.Diary
{
    [GuiModule("c67c1ee9-8029-4849-8918-6cf3153497fe", "NewDiary", "Ray Shaw(demogodyou@gmail.com)")]
    public partial class frmEnhancedDiaryEditor : GuiModuleUIBase
    {
        #region Constructors

        private DiaryInfo _diary;
        private object _sender;
        private readonly int MAX_TITLE_LENGTH = 64; //标题文字长度
        private bool _autoSave = true; //是否自动保存
        private bool _isModified = false;

        public DiaryInfo Diary
        {
            get { return _diary; }
            set
            {
                if (_diary == value) { return; }

                _diary = value;
                DisplayDiary();
            }
        }

        #endregion

        #region Constructors

        public frmEnhancedDiaryEditor()
        {
            InitializeComponent();

        }

        #endregion

        #region Methods

        /// <summary>
        /// 显示可选日记组信息。
        /// </summary>
        private void ShowDiaryGroupNames()
        {
            DataTable table = Utils.GetDataAccessServiceInstance().GetDataTable("select * from DiaryGroupInfo");

            cmbDiaryGroup.DataSource = table;
            cmbDiaryGroup.DisplayMember = "Name";
            cmbDiaryGroup.ValueMember = "Id";
        }

        void txtContent_ModifiedChanged(object sender, EventArgs e)
        {
            _isModified = true;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            ShowDiaryGroupNames();
        }

        /// <summary>
        /// 显示日记信息。
        /// </summary>
        private void DisplayDiary()
        {
            if (_diary == null)
            {
                lblDate.Text = DateTime.Now.ToLongDateString();
                lblTitle.Caption = string.Empty;
                diaryTagButton.Tags = string.Empty;
                emotionButtonControl.Emotion = null;
                richTextBoxContent.Text = string.Empty;
                //cmbDiaryGroup.SelectedIndex = -1;

                _isModified = true;

                return;
            }

            lblDate.Text = _diary.CreatedDatetime.ToLongDateString();
            lblTitle.Caption = _diary.Title;
            diaryTagButton.Tags = _diary.Tag;
            emotionButtonControl.Emotion = EmotionInfo.GetEmotionInfoById(_diary.EmotionId);
            richTextBoxContent.Text = _diary.Content;
            cmbDiaryGroup.SelectedValue = _diary.DiaryGroupId;

            lblModifiedDatetime.Text = string.Format("修改于: {0}", _diary.UpdateDatetime);
            lblModifiedDatetime.Visible = _diary.CreatedDatetime != _diary.UpdateDatetime;

            _isModified = false;
        }

        /// <summary>
        /// 输入数据合法性检查。
        /// </summary>
        /// <returns></returns>
        private bool CheckIfInputOk(bool allowShowMessage)
        {
            if (this.richTextBoxContent.Text.Trim().Length == 0)
            {
                if (allowShowMessage)
                {
                    ShowMessage("请您先输入日记内容，再保存。");
                }

                richTextBoxContent.Focus();
                richTextBoxContent.SelectAll();

                return false;
            }

            return true;
        }

        public override string GetSettingsKeyName()
        {
            return this.Name;
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);

            if (_autoSave && NeedSave())
            {
                if (!CheckIfInputOk(true)) { e.Cancel = true; return; }

                Save(false);
            }
        }

        /// <summary>
        /// 是否需要保存。
        /// </summary>
        /// <returns></returns>
        private bool NeedSave()
        {
            return (_isModified && this.richTextBoxContent.Text.Trim().Length > 0 && (this.DialogResult != DialogResult.Cancel));
        }

        /// <summary>
        /// 如日记类别不存在，则新建。
        /// </summary>
        private void CreateDiaryGroupIfNotExists()
        {
            if ((cmbDiaryGroup.FindString(cmbDiaryGroup.Text) != -1) ||
                (string.IsNullOrEmpty(cmbDiaryGroup.Text.Trim()))) { return; }

            string diaryGroupName = cmbDiaryGroup.Text;

            DiaryGroupInfo diaryGroupInfo = new DiaryGroupInfo();
            diaryGroupInfo.Name = diaryGroupName;
            diaryGroupInfo.CreatedDatetime = DateTime.Now;

            if (!DbObjectMappingHelper.Create<DiaryGroupInfo>(diaryGroupInfo))
            {
                ShowMessage("创建新的日记类别[" + cmbDiaryGroup.Text + "]失败。");
            }
            else //重新加载日记类别
            {
                ShowDiaryGroupNames();
                cmbDiaryGroup.Text = diaryGroupName;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save(true);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            Close();
        }

        /// <summary>
        /// 保存日记。
        /// </summary>
        private void Save(bool allowShowMessage)
        {
            if (!CheckIfInputOk(allowShowMessage)) { return; }

            //如需要，则创建日记类别
            CreateDiaryGroupIfNotExists();

            DiaryService service = new DiaryService();
            DbOperationStyle style = DbOperationStyle.Insert;

            //如果没有输入日记标题，则自动取正文前 MAX_TITLE_LENGTH 个字符作为日记标题。
            if (lblTitle.Caption.Trim().Length == 0)
            {
                lblTitle.Caption =
                    (this.richTextBoxContent.Text.Trim().Length >= MAX_TITLE_LENGTH ?
                    richTextBoxContent.Text.Trim().Substring(0, MAX_TITLE_LENGTH) : richTextBoxContent.Text.Trim());
            }

            if (_diary == null || string.IsNullOrEmpty(_diary.Id)) //新增
            {
                _diary = new DiaryInfo();
                _diary.Content = richTextBoxContent.Text;
                _diary.Id = Guid.NewGuid().ToString();
                _diary.Title = lblTitle.Caption;
                _diary.Tag = diaryTagButton.Tags;
                _diary.EmotionId = (emotionButtonControl.Emotion != null ? emotionButtonControl.Emotion.Id : -1);
                _diary.DiaryGroupId = (cmbDiaryGroup.SelectedValue != null ? Convert.ToInt64(cmbDiaryGroup.SelectedValue) : 1);
                _diary.CreatedDatetime = DateTime.Now;
                _diary.UpdateDatetime = _diary.CreatedDatetime;
            }
            else  //更新
            {
                style = DbOperationStyle.Update;

                _diary.Content = richTextBoxContent.Text;
                _diary.Title = lblTitle.Caption;
                _diary.Tag = diaryTagButton.Tags;
                _diary.EmotionId = (emotionButtonControl.Emotion != null ? emotionButtonControl.Emotion.Id : -1);
                _diary.DiaryGroupId = (cmbDiaryGroup.SelectedValue != null ? Convert.ToInt64(cmbDiaryGroup.SelectedValue) : 1);
                _diary.UpdateDatetime = _diary.CreatedDatetime;
            }

            if (service.SaveDiary(_diary, style))
            {
                _isModified = false;
                DiaryInfoListItemControl diaryInfoControl = _sender as DiaryInfoListItemControl;

                lblModifiedDatetime.Visible = _diary.CreatedDatetime != _diary.UpdateDatetime;
                lblModifiedDatetime.Text = string.Format("修改于: {0}", _diary.UpdateDatetime);

                if (diaryInfoControl != null)
                {
                    diaryInfoControl.Diary = DiaryInfo.DecryptDiaryInfo(_diary);
                }

                OwnerShell.NotifyMessage(this, new MessageReceivedEventArgs(MessageDefinition.Refresh,
                    "c67c1ee9-8029-4849-8918-6cf3153497fe", "3b42c11a-18e8-476c-b6c3-87137d093c67"));

                if (allowShowMessage)
                {
                    ShowMessage("保存成功。");
                }
                //DelayClose();
            }
            else
            {
                if (allowShowMessage)
                {
                    ShowMessage("保存失败。");
                }
            }
        }

        public override void SetParameter(object parameter, object sender)
        {
            base.SetParameter(parameter, sender);

            _sender = sender;
            DiaryInfo diaryInfo = parameter as DiaryInfo;

            Diary = diaryInfo;
        }

        protected override void OnKeyDown(KeyEventArgs e)
        {
            base.OnKeyDown(e);

            if (e.Control)
            {
                switch (e.KeyCode)
                {
                    case Keys.S:
                        {
                            Save(true);
                            break;
                        }
                }
            }
        }

        public override void OnMessageReceived(object sender, MessageReceivedEventArgs e)
        {
            base.OnMessageReceived(sender, e);

            if (e.TargetModuleId.Equals("3b42c11a-18e8-476c-b6c3-87137d093c67", StringComparison.CurrentCultureIgnoreCase))
            {
                switch (e.MessageInfo)
                {
                    case MessageDefinition.CloseNow: //立即关闭
                        {
                            //如果 Parameter 传递的是当前日记的编码，则表示此消息的意义是，此编号的日记已经被删除了，要立即关闭当前编辑日记的窗体。
                            if (_diary != null && e.Parameter != null
                                && e.Parameter.ToString().Equals(_diary.Id, StringComparison.CurrentCultureIgnoreCase))
                            {
                                Close();
                            }

                            break;
                        }
                }
            }
        }

        /// <summary>
        /// 新增日记。
        /// </summary>
        private void NewDiary()
        {
            if (_isModified) { Save(false); } //如果需要，先保存当前日记。

            lblDate.Text = DateTime.Now.ToLongDateString();
            lblTitle.Caption = string.Empty;
            richTextBoxContent.Clear();
            diaryTagButton.Tags = string.Empty;
            emotionButtonControl.Emotion = null;

            _isModified = false;
        }

        #endregion

        private void contextMenuStrip_Opening(object sender, CancelEventArgs e)
        {
            miUndo.Enabled = richTextBoxContent.CanUndo;
            miCopy.Enabled = richTextBoxContent.SelectionLength > 0;
            miDelete.Enabled = richTextBoxContent.SelectionLength > 0;
            miCut.Enabled = miDelete.Enabled;
            miSelectAll.Enabled = richTextBoxContent.Text.Length > 0;
        }

        private void miUndo_Click(object sender, EventArgs e)
        {
            richTextBoxContent.Undo();
        }

        private void miCut_Click(object sender, EventArgs e)
        {
            richTextBoxContent.Cut();
        }

        private void miCopy_Click(object sender, EventArgs e)
        {
            richTextBoxContent.Copy();
        }

        private void miPatse_Click(object sender, EventArgs e)
        {
            richTextBoxContent.Paste();
        }

        private void miDelete_Click(object sender, EventArgs e)
        {
            richTextBoxContent.SelectedText = string.Empty;
        }

        private void miSelectAll_Click(object sender, EventArgs e)
        {
            richTextBoxContent.SelectAll();
        }

        private void btnNewDiary_Click(object sender, EventArgs e)
        {
            NewDiary();
        }
    }
}
